package com.yic.module.mes.controller.admin.process;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yic.framework.common.enums.CommonStatusEnum;
import com.yic.framework.common.util.collection.CollectionUtils;
import com.yic.module.base.api.center.CenterApi;
import com.yic.module.base.api.center.dto.CenterRespDTO;
import com.yic.module.base.api.factory.FactoryApi;
import com.yic.module.base.api.factory.dto.FactoryRespDTO;
import com.yic.module.system.api.dept.DeptApi;
import com.yic.module.system.api.dept.dto.DeptRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.yic.framework.common.pojo.PageResult;
import com.yic.framework.common.pojo.CommonResult;
import static com.yic.framework.common.pojo.CommonResult.success;

import com.yic.framework.excel.core.util.ExcelUtils;

import com.yic.framework.operatelog.core.annotations.OperateLog;
import static com.yic.framework.operatelog.core.enums.OperateTypeEnum.*;

import com.yic.module.mes.controller.admin.process.vo.*;
import com.yic.module.mes.dal.dataobject.process.ProcessDO;
import com.yic.module.mes.convert.process.ProcessConvert;
import com.yic.module.mes.service.process.ProcessService;

@Tag(name = "管理后台 - 工艺信息")
@RestController
@RequestMapping("/mes/process")
@Validated
public class ProcessController {

    @Resource
    private ProcessService processService;
    @Resource
    private DeptApi deptApi;
    @Resource
    private FactoryApi factoryApi;
    @Resource
    private CenterApi centerApi;

    @PostMapping("/create")
    @Operation(summary = "创建工艺信息")
    @PreAuthorize("@ss.hasPermission('mes:process:create')")
    public CommonResult<Long> createProcess(@Valid @RequestBody ProcessCreateReqVO createReqVO) {
        return success(processService.createProcess(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新工艺信息")
    @PreAuthorize("@ss.hasPermission('mes:process:update')")
    public CommonResult<Boolean> updateProcess(@Valid @RequestBody ProcessUpdateReqVO updateReqVO) {
        processService.updateProcess(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工艺信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:process:delete')")
    public CommonResult<Boolean> deleteProcess(@RequestParam("id") Long id) {
        processService.deleteProcess(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工艺信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:process:query')")
    public CommonResult<ProcessRespVO> getProcess(@RequestParam("id") Long id) {
        ProcessDO process = processService.getProcess(id);
        return success(ProcessConvert.INSTANCE.convert(process));
    }

    @GetMapping("/list")
    @Operation(summary = "获得工艺信息列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('mes:process:query')")
    public CommonResult<List<ProcessRespVO>> getProcessList(@RequestParam("ids") Collection<Long> ids) {
        List<ProcessDO> list = processService.getProcessList(ids);
        return success(ProcessConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得工艺信息分页")
    @PreAuthorize("@ss.hasPermission('mes:process:query')")
    public CommonResult<PageResult<ProcessRespVO>> getProcessPage(@Valid ProcessPageReqVO pageVO) {
        PageResult<ProcessDO> pageResult = processService.getProcessPage(pageVO);
        List<ProcessDO> list = pageResult.getList();
        // 获取部门数据
        Set<Long> deptIds = CollectionUtils.convertSet(list, ProcessDO::getDeptId);
        List<DeptRespDTO> deptList = deptApi.getDeptList(deptIds);
        Map<Long, DeptRespDTO> deptMap = CollectionUtils.convertMap(deptList, DeptRespDTO::getId);
        // 获取封装数据
        List<ProcessRespVO> respVOs = new ArrayList<>(list.size());
        if (CollUtil.isNotEmpty(list)){
            //由于工厂数据、工作中心数据在缓存中有数据，可以循环遍历组装赋值
            list.forEach(process -> {
                ProcessRespVO respVO = ProcessConvert.INSTANCE.convert(process);
                DeptRespDTO dept = deptMap.get(process.getDeptId());
                if (ObjectUtil.isNotEmpty(dept)){
                    respVO.setDeptName(dept.getName());
                }
                FactoryRespDTO factory = factoryApi.getFactory(process.getFactoryId());
                if (ObjectUtil.isNotEmpty(factory)){
                    respVO.setFactoryName(factory.getName());
                }
                CenterRespDTO center = centerApi.getCenter(process.getCenterId());
                if (ObjectUtil.isNotEmpty(center)) {
                    respVO.setCenterName(center.getName());
                }
                respVOs.add(respVO);
            });
        }
        return success(new PageResult<>(respVOs, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出工艺信息 Excel")
    @PreAuthorize("@ss.hasPermission('mes:process:export')")
    @OperateLog(type = EXPORT)
    public void exportProcessExcel(@Valid ProcessExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<ProcessDO> list = processService.getProcessList(exportReqVO);
        // 导出 Excel
        List<ProcessExcelVO> datas = ProcessConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "工艺信息.xls", "数据", ProcessExcelVO.class, datas);
    }

    @GetMapping("/list-all-simple")
    @Operation(summary = "获取工序精简信息列表", description = "只包含被开启的工序，主要用于前端的下拉选项")
    public CommonResult<List<ProcessSimpleRespVO>> getSimpleProcessList(@Valid ProcessPageReqVO pageVO) {
        // 获得品牌列表，只要开启状态的
        List<ProcessDO> list = processService.getProcessList(pageVO);
        // 排序后，返回给前端
        list.sort(Comparator.comparing(ProcessDO::getSort));
        return success(ProcessConvert.INSTANCE.convertList03(list));
    }

}
